(function(win){
	var Z = win.Z, Bundle = Z.Bundle, BundleList = Z.BundleList,
		bundle = new Bundle({'tmpl' : 'client'}), form, loader;
		
	bundle.addEvent('a.add', 'click', function(){
		form.clear().open();
		return false;
	});

	bundle.addEvent('thead a', 'click', function(){
		var field = $(this).data('field'),
		direction = (typeof $(this).data('direction') == 'undefined') ? 1 : $(this).data('direction');
		$(this).data('direction', direction * -1);
		loader.load({'orderField' : field, 'orderDirection' : direction});
		return false;
	});

	bundle.addEvent('tbody', 'click', 'a.edit', function(){
		var id = $(this).parent().siblings().first().find(':checkbox').val();
		Z.ajax({
			'url' : Z.route('client','find'),
			'data' : {'id' : id},
			'success' : function(data){
				form.open().fill(data);
			}
		});
		return false;
	});

	bundle.onload = function(){
		Z.ajax({
			'url' : Z.route('server', 'records'),
			'data' : {pageSize : 50},
			'success' : function(data) {
				form = new Z.Form({
					'title' : '添加/修改应用',
					'content' : win.tmpl(bundle.find('script.form-tmpl').html(), data),
					'width' : 500,
					'action' : Z.route('client','set')
				});
				form.onsubmit = function() {
					loader.reload();
				};
			}
		});

		loader = new Z.Loader({
			'url': Z.route('client', 'records'),
			'listTmpl': bundle.find('script.list-tmpl').html(),
			'list': bundle.find('tbody'),
			'pagination': bundle.find('tfoot td')
		});

		loader.load({'pageSize' : 20});

	};
	
	BundleList.append(bundle);
})(window);